import {routerRedux} from 'dva/router';
import api from '../api';
import {time} from '../config'
import moment from 'moment'
let timer

export default {
  namespace : 'realtimeTarget',
  state : {
    data:[]
  },
  subscriptions : {
    setup({dispatch, history}) {
      history.listen((location) => {
        clearInterval(timer)
        const {pathname,query}=location
        if( pathname === '/tradeAnalysis/tca/realtimeTarget' ){
          const {from,...newQuery}=query
          if(from){
            dispatch({
              type:'changeRouter',
              payload:{
                pathname,
                query:newQuery
              }
            })
          }else{
            dispatch({
              type: 'requestResult',
              payload:query
            })
            timer=setInterval(() => {
              const nowTime=moment().format('H.m')
              if(nowTime>9.30&&nowTime<15.30){
                dispatch({
                  type: 'requestResult',
                  payload:query
                })
              }
        		}, time)
          }
        }
      })
    }
  },
  effects : {
    // 查询结果
    * requestResult({payload}, {call, put,select}){
      const response = yield call(api.tca.getRealtimeTarget, payload);
      yield put({type: 'querySuccess', payload: {
        key:payload.at,
        data:response.data
      }});
    },
    // 改变路由
    * changeRouter({payload}, {put}){
      clearInterval(timer)
      yield put(routerRedux.push(payload))
    }
  },
  reducers : {
    querySuccess(state, {payload}) {
      const keyIndex=state.data.findIndex((item, index, arr)=>item.key===payload.key)
      if(keyIndex>-1){
        state.data.splice(keyIndex,1,payload)
      }else{
        state.data.push(payload)
      }

      return {
        ...state
      }

    }
  }
};
